//
//  YBCloudComputerBuyVC.swift
//  Moonlight
//
//  Created by Penlon Kim on 2023/6/30.
//  Copyright © 2023 Moonlight Game Streaming Project. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON
import HandyJSON
import EachNavigationBar
import SVProgressHUD
import InAppPurchase

class YBCloudComputerBuyVC: BaseVC {
    
    private let kGoodsId: String
    private var payType = 0  // 支付方式
    private var selectedModel: YBBuyModel? // 选中的套餐
    
    init(goodsId: String) {
        kGoodsId = goodsId
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        startInTransactionObserver()
        
        navigation.item.title = "云电脑"
        navigation.item.rightBarButtonItem = UIBarButtonItem(customView: newsBtn)
        view.backgroundColor = .lightGray242Dark17
        
        view.addSubviews([tableView, bottomView])
        bottomView.addSubviews([totalPriceLabel, payBtn])
        
        bottomView.snp.makeConstraints { make in
            make.left.bottom.right.equalToSuperview()
            make.height.equalTo(kBottomSafeHeight+56)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top)
        }
        
        payBtn.snp.makeConstraints { make in
            make.top.equalTo(12)
            make.right.equalTo(-20)
            make.size.equalTo(CGSizeMake(kScreenWidth*0.357, 40))
        }
        
        totalPriceLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.centerY.equalTo(payBtn)
        }
        
        // 请求数据
        self.requestItenPriceConfig()
        self.addNoc()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        tableView.selectRow(at: IndexPath(row: 0, section: 0), animated: true, scrollPosition: .none)
    }
    
    fileprivate func addNoc() {
        NotificationCenter.default.addObserver(self, selector: #selector(paySuccess), name: .didPaySuccess, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(payError), name: .didPayError, object: nil)
    }
    
    // 支付成功的通知
    @objc func paySuccess() {
        SVProgressHUD.showSuccess(withStatus: "失败成功")
    }
    
    // 支付失败的通知
    @objc func payError() {
        SVProgressHUD.showError(withStatus: "失败失败")
    }
    
    // MARK: - lazy
    lazy var vm: YBCloudComputerViewModel = {
        let vm = YBCloudComputerViewModel()
        return vm
    }()
    
    private lazy var tableView: BKGestureTableView = {
        let tv = BKGestureTableView(frame: .zero, style: .grouped)
        tv.estimatedRowHeight = 44
        tv.rowHeight = UITableView.automaticDimension
        tv.delegate = self
        tv.dataSource = self
        tv.gestureDelegate = self
        tv.separatorStyle = .none
        tv.showsVerticalScrollIndicator = false
        tv.bk_setHeaderFooter(headerV: tableHeader)
        if #available(iOS 15.0, *) {
            tv.sectionHeaderTopPadding = 0
        }
        tv.register(cellWithClass: YBCloudComputerBuyCell.self)
        tv.register(cellWithClass: YBCloudComputerPayCell.self)
        return tv
    }()
    
    private lazy var tableHeader: YBCloudComputerTableHeader = {
        let header = YBCloudComputerTableHeader()
        return header
    }()
    
    private lazy var newsBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "icon_cloudcomputer_news"), for: .normal)
        btn.bk_addTarget { sender in
            let messageVC = YBMessageVC()
            self.navigationController?.pushViewController(messageVC, animated: true)
        }
        return btn
    }()
    
    private lazy var bottomView: UIView = {
        let view = UIView(color: .lightWhiteDark27)
        view.bk_addShadowStyleWith(cornerRadius: 20, corners: [.topLeft, .topRight], with: .top, shadowColor: .lightBlackDarkWhite.withAlphaComponent(0.5))
        return view
    }()
    
    private lazy var totalPriceLabel = self.bk_addLabel(bgColor: .clear)
    
    private lazy var payBtn: UIButton = {
        let btn = self.bk_addGradientButton(title: "确认支付", font: .systemFont(ofSize: 14, weight: .medium), titleColor: .white, gradientSize: CGSizeMake(kScreenWidth*0.357, 40), colors: [kRGBColor(88, 182, 255), kRGBColor(40, 128, 237)])
        btn.bk_addStyleWith(cornerRadius: 20, corners: .allCorners)
        btn.bk_addTarget { [unowned self] sender in
            
            // 开始支付
            if payType == 0 {
                HintTool.toast("请选择支付方式")
            }else {
                // 开始请求支付
                // 调保存快照，再接着调新增订单，在调用预支付
                guard let model = self.selectedModel else {
                    return
                }
                if payType == 3 {
                    SVProgressHUD.show(withStatus: "请求中....")
                    InAppPurchase.default.purchase(productIdentifier: model.productId) { result in
                        switch result {
                        case .success(let response):
                            switch response.state {

                            case .purchased:
                                print("[PURCHASED] \(response.transaction.transactionIdentifier ?? "nil")")
                                // 支付成功
                                DispatchQueue.main.async { [self] in
                                    SVProgressHUD.dismiss()
                                    SVProgressHUD.showSuccess(withStatus: "购买成功")
                                    
                                    if let appStoreReceiptURL = Bundle.main.appStoreReceiptURL,
                                       FileManager.default.fileExists(atPath: appStoreReceiptURL.path) {
                                        
                                        let receiptData = try? Data(contentsOf: appStoreReceiptURL)
                                        let receiptString = receiptData?.base64EncodedString(options: [])
                                        // 你可以将这个 base64 编码的字符串发送到你的服务器，然后从服务器验证。
                                        
                                        // 回传数据到服务器
                                        model.receipt = receiptString ?? ""
                                        vm.startPay(buyModel: model, payType: payType) { [self] pram in
                                            print(pram as Any)
                                        }
                                    }
                                }
                            case .restored:
                                print("[RESTORED] \(response.transaction.transactionIdentifier ?? "nil")")
                            case .deferred:
                                print("[DEFERRED] \(response.transaction.transactionIdentifier ?? "nil")")
                            }
                        case .failure(let error):
                            print(error)
                            SVProgressHUD.showError(withStatus: "内购信息请求失败")
                        }
                    }
                }else {
                    // 开始支付
                    vm.startPay(buyModel: model, payType: payType) { [self] pram in
//                        if payType == 2 {
//                            // 创建支付请求对象
//                            let req = PayReq()
//                            // 设置支付请求参数
//                            req.openID = "YOUR_PARTNER_ID"
//                            req.partnerId = "YOUR_PARTNER_ID"
//                            req.prepayId = "YOUR_PREPAY_ID"
//                            req.nonceStr = "YOUR_NONCE_STR"
//                            req.timeStamp = UInt32(Date().timeIntervalSince1970)
//                            req.package = "YOUR_PACKAGE"
//                            req.sign = "YOUR_SIGN"
//                            // 发起支付
//                            WXApi.send(req)
//
//                        }else if payType == 1 {
//                            AlipaySDK.defaultService()?.payOrder(pram, fromScheme: "xboxSchemeForAliPay", callback: { result in
//                                // 处理支付结果
//                                if let resultStatus = result?["resultStatus"] as? String {
//                                    if resultStatus == "9000" {
//                                        // 支付成功
//                                        self.paySuccess()
//                                    } else {
//                                        // 支付失败
//                                        self.payError()
//                                    }
//                                }
//                            })
//                        }
                    }
                }
            }
        }
        return btn
    }()

    func startInTransactionObserver() {
        InAppPurchase.default.addTransactionObserver { result in
            DispatchQueue.main.async {
                SVProgressHUD.dismiss()
            }
            switch result {
            case .success(let response):
                switch response.state {
                case .purchased:
                    print("[PURCHASED] \(response.transaction.transactionIdentifier ?? "nil")")
                    
                case .restored:
                    print("[RESTORED] \(response.transaction.transactionIdentifier ?? "nil")")
                case .deferred:
                    print("[DEFERRED] \(response.transaction.transactionIdentifier ?? "nil")")
                }
            case .failure(let error):
                print(error)
            }
        }
    }
    
    // 请求价格配置（商品详情）
    func requestItenPriceConfig() {
        self.vm.req_GetInfo(kGoodsId) { [weak self] ok, obj, msg, code in
            if ok {
                guard let js = obj as? JSON,
                      let detailModel = YBGoodsDetailModel.deserialize(from: js[NetDataKey].dictionaryObject),
                      let data = js[NetDataKey]["goodsLadderVos"].arrayObject,
                      let models = [YBBuyModel].deserialize(from: data) as? [YBBuyModel] else { return }
                self?.vm.detailModel = detailModel
                self?.vm.buyModels = models
                self?.tableView.reloadData()
                
                self?.selectedModel = self?.vm.buyModels.firstK
                self?.reloadTotalPrice()
            } else {
                HintTool.toast(msg)
            }
        }
    }
}


// MARK: - Private
extension YBCloudComputerBuyVC {
    
    private func reloadTotalPrice() {
        totalPriceLabel.attributedText = NSMutableAttributedString("总计：") { $0
            .font(.systemFont(ofSize: 14))
            .foregroundColor(ColorDef.gray102)
        }.addText(" ¥\(self.selectedModel?.priceTag ?? 0)") { $0
            .font(.systemFont(ofSize: 17, weight: .semibold))
            .foregroundColor(kRGBColor(236, 68, 60))
        }
    }
    
}

// MARK: - BKGestureTableViewDelegate
extension YBCloudComputerBuyVC: BKGestureTableViewDelegate {
    
    func gestureTableViewGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        // 禁止banner左右滑动的时候,上下左右都可以滚动
        if otherGestureRecognizer == tableHeader.cardView._collectionView.panGestureRecognizer { return false }
        return gestureRecognizer is UIPanGestureRecognizer && otherGestureRecognizer is UIPanGestureRecognizer
    }
    
}

// MARK: - UITableView代理
extension YBCloudComputerBuyVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 10
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return vm.buyModels.count > 0 ? vm.buyModels.count + 1 : 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == vm.buyModels.count {
            // 支付
            let cell = tableView.dequeueReusableCell(withClass: YBCloudComputerPayCell.self, for: indexPath)
            cell.selectedTypeBlock = { selectedType in
                self.payType = selectedType
            }
            return cell
        } else {
            // 数据
            let cell = tableView.dequeueReusableCell(withClass: YBCloudComputerBuyCell.self, for: indexPath)
            let model = vm.buyModels[indexPath.section]
            cell.updateCell(by: model)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == vm.buyModels.count {
            return
        }
        let model = vm.buyModels[indexPath.section]
        self.selectedModel = model
        self.reloadTotalPrice()
    }
    
}

// 通知
extension Notification.Name {
    static let didPaySuccess = Self("DID_PAYSUCCESS_NOTIFICATION")       // 支付成功
    static let didPayError = Self("DID_PAYERROR_NOTIFICATION")        // 支付失败
}

